//  对于指定的描述符打印文件标志
//  fileflags.c
//  programing_in_unix
//
//  Created by homcin on 2017/12/9.
//  Copyright © 2017年 tarshe. All rights reserved.
//

#include "apue.h"
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int val;
    
    if (argc != 2)
        err_quit("usage: a.out <descriptor#>");
    
    if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
        err_sys("fcntl error for fd %d", atoi(argv[1]));
    
    switch (val & O_ACCMODE) {
        case O_RDONLY:
            printf("read only");
            break;
        
        case O_WRONLY:
            printf("write only");
            break;
            
        case O_RDWR:
            printf("read write");
            break;
            
        default:
            err_dump("unknown access mode");
    }
    
    if (val & O_APPEND)
        printf(", append");
    if (val & O_NONBLOCK)
        printf(", noblocking");
    if (val & O_SYNC)
        printf(", synchronous writes");
    
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC) && (O_FSYNC != O_SYNC)
    if (val & O_FSYNC)
        printf(", synchronous writes");
#endif
    
    putchar('\n');
    exit(0);
    
}

/*
 ➜  programing_in_unix ./fileflags.out 0 < /dev/tty
 read only
 ➜  programing_in_unix ./fileflags.out 1 > temp.foo
 ➜  programing_in_unix cat temp.foo
 write only
 ➜  programing_in_unix vim temp.foo
 ➜  programing_in_unix ./fileflags.out 2 2>>temp.foo
 write only, append
 ➜  programing_in_unix ./fileflags.out 5 5<>temp.foo
 read write
*/
